package util;
import android.content.Context;
import android.graphics.Bitmap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

import app.MyApplication;
import data.SharedPreferencesUtils;

/**
 * Created by Administrator on 2016/5/5.
 * 获取网络数据工具类
 */
public class GreenTreeNetworkUtil {

    private OnGTNBitmapClickListener mOnGTNBitmapClickListener;
    private static volatile GreenTreeNetworkUtil greenTreeNetwork;
    protected GreenTreeNetworkUtil(){

    }

    /**
     *单利
     */
    public static GreenTreeNetworkUtil getInstance() {
        if (greenTreeNetwork == null) {
            synchronized (GreenTreeNetworkUtil.class){
                if(greenTreeNetwork == null){
                    greenTreeNetwork = new GreenTreeNetworkUtil();
                }
            }
        }
        return greenTreeNetwork;
    }

    /**
     * get请求
     */
    public void doGet(final String requestUrl, Map<String, Object> params, final RequestDataCallback callback) {
        RequestParams requestParams = new RequestParams(requestUrl);
        requestParams.setConnectTimeout(10000);

        if (params != null) {
            Set<Map.Entry<String, Object>> set = params.entrySet();

            for (Map.Entry<String, Object> entry : set) {
                if (entry.getValue() != null && !"".equals(entry.getValue())) {
                    requestParams.addQueryStringParameter(
                            entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
        }
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override public void onSuccess(String result) {
                callback.onSuccess(result);
            }

            @Override public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override public void onCancelled(CancelledException cex) {

            }

            @Override public void onFinished() {

            }
        });
    }

    /**
     * post请求
     * setConnectTimeout 为超时时间
     * 1 为默认10秒时间
     * 其他则用传过来的数
     */
    public void doPost(final Context context,String requestUrl,int connect,Map<String, Object> params, final RequestDataCallback callback) {
        RequestParams requestParams = new RequestParams(requestUrl);
        if(connect == 1){
            requestParams.setConnectTimeout(10000);
        }else {
            requestParams.setConnectTimeout(connect);
        }

        if (params != null) {
            Set<Map.Entry<String, Object>> set = params.entrySet();

            for (Map.Entry<String, Object> entry : set) {
                if (entry.getValue() != null && !"".equals(entry.getValue().toString().trim())) {
                    requestParams.addBodyParameter(
                            entry.getKey(),
                            String.valueOf(entry.getValue()));
                }
            }
        }

        x.http().post(requestParams, new Callback.CommonCallback<String>() {

            //成功时调用
            @Override
            public void onSuccess(String result) {
                callback.onSuccess(result);
                setNoticeState(result,context);
            }

            //请求异常后的回调方法  onErrorjava.net.SocketTimeoutException: failed to connect to api.szaltair.com/123.207.119.229 (port 8080) after 8000ms
            //
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                callback.onFailure(ex);
            }

            //主动调用取消请求的回调方法
            @Override
            public void onCancelled(CancelledException cex) {

            }

            //结束时调用
            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * post请求用户信息,传入的参数为纯数组数组
     */
    public void doPostArray(String requestUrl,
                            Map<String, Object> params,
                            final RequestDataCallback callback) {
        RequestParams requestParams = new RequestParams(requestUrl);
        if (params != null) {
            Set<Map.Entry<String, Object>> set = params.entrySet();
            for (Map.Entry<String, Object> entry : set) {
                if (entry.getValue() != null && !"".equals(entry.getValue())) {
                    List<String> l = (List<String>) entry.getValue();
                    if (l != null) {
                        for (String s : l) {
                            requestParams.addBodyParameter(entry.getKey(), s);
                        }
                    }
                }
            }
        }

        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                callback.onSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                callback.onFailure(ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    /**
     * 上传文件(或者普通请求)
     */
    public void doPostFile(String requestUrl,Map<String, Object> params,final RequestDataCallback callback){
        RequestParams requestParams = new RequestParams(requestUrl);
        requestParams.setConnectTimeout(30000);
        requestParams.setMultipart(true);

        if (params != null) {
            Set<Map.Entry<String, Object>> set = params.entrySet();

            for (Map.Entry<String, Object> entry : set) {
                if (entry.getValue() != null && !"".equals(entry.getValue().toString().trim())) {
                    if (entry.getKey().length()>=3 && "file".equals(entry.getKey().substring(0,4))) {//文件
                        requestParams.addBodyParameter(
                                entry.getKey(),
                                (File) entry.getValue());
                    } else {
                        requestParams.addBodyParameter(
                                entry.getKey(),
                                String.valueOf(entry.getValue()));
                    }
                }
            }
        }

        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                    callback.onSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                callback.onFailure(ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 判断是否要显示公共
     */
    private void setNoticeState(String json,Context context){
        try {
            JSONObject jsonObject = new JSONObject(json);
            if(jsonObject.getInt("code") == 1){
                if(jsonObject.has("notice")){
                    JSONObject jsonObject1 =  jsonObject.getJSONObject("notice");
                    String noticeId = jsonObject1.getString("noticeId");
                    String noticeUrl = jsonObject1.getString("noticeUrl");
                    int noticeType = jsonObject1.getInt("noticeType");
                    JSONArray jsonArray = jsonObject1.getJSONArray("noticeArea");
                    setNotice(context,jsonArray,noticeId,noticeUrl,noticeType);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     *查看系统公告 看是否需要展示
     */
    private void setNotice(Context context, JSONArray jsonArray, String noticeId, String noticeUrl,int noticeType){
        for (int i = 0; i <jsonArray.length(); i++) {
            try {
                int intAreaid = jsonArray.getInt(i);
                if(MyApplication.getApp().getSiteAreaid() == intAreaid){
                    LogUtil.eE("","...setNotice....................."+noticeId);
                    if(noticeType == 1){
                        JumpActivityUtils.getInstance().jumpWebView(context,noticeUrl,"公告");
                    }else {
                        if(!SharedPreferencesUtils.getParam(context,HomeUtil.mAppNoticeNoticeId,"").equals(noticeId)){
                            SharedPreferencesUtils.setParam(context,HomeUtil.mAppNoticeNoticeId,noticeId);
                            JumpActivityUtils.getInstance().jumpWebView(context,noticeUrl,"公告");
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 定义接口 用于Bitmap  的回调
     */
    public interface OnGTNBitmapClickListener {
        void onItemClick(Bitmap bitmap);
    }

    public void setOnGTNBitmapClickListener(OnGTNBitmapClickListener clickListener) {
        this.mOnGTNBitmapClickListener = clickListener;
    }
}
